<template>
  <view class="fix-top-window">
    <view class="uni-header">
      <view class="uni-group">
        <!-- <uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" /> -->
        <text class="uni-title">字典选项管理-{{tableData.parent.name}}管理</text>
      </view>
      <view class="uni-group">
        <button class="uni-button" type="primary" size="mini" @click="showDialog()">
          {{$t('common.button.add')}}
        </button>
		<button class="uni-button" size="mini" type="warn" v-if="uniIDHasPermission('wdd')" 
		:disabled="!tableData.selectedIndexArray.length" @click="removeDataByIds()">{{ $t('common.button.batchDelete') }}</button>
		<navigator url="/pages/wallpaper/dict/list">
			<button type="default" size="mini">返回列表</button>
		</navigator>
      </view>
    </view>
    <view class="uni-container">
      <uni-table ref="tableRef" type="selection" :emptyText="$t('common.empty')" @selection-change="selectionChange" border stripe>
        <uni-tr>
          <uni-th align="center">编码</uni-th>
          <uni-th align="center">显示文本</uni-th>
          <uni-th align="center">详细说明</uni-th>
          <uni-th align="center">状态</uni-th>
          <uni-th align="center">排序</uni-th>
          <uni-th align="center">操作</uni-th>
        </uni-tr>
        <uni-tr v-for="(item,index) in tableData.list" :key="index">
          <uni-td align="center">{{item.code}}</uni-td>
          <uni-td align="center">{{item.text}}</uni-td>
          <uni-td align="center">{{item.description}}</uni-td>
          <uni-td align="center">
            <switch :checked='item.status' style="transform:scale(0.7)" 
              @change="toggleFieldChange(item.code, 'status')" />
          </uni-td>
          <uni-td align="center">{{item.sort}}</uni-td>
          <uni-td align="center">
            <view class="uni-group">
              <button class="uni-button" size="mini" type="primary" @click="showDialog(item.code, dictId)">
                {{ $t('common.button.edit') }}
              </button>
              <button class="uni-button" size="mini" type="warn" 
                @click="removeDataByIds([item.code])">
                {{ $t('common.button.delete') }}
              </button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
	  <view class="uni-pagination-box">
	    <uni-pagination show-icon show-page-size :page-size="query.pageSize" v-model="query.page"
	      :total="tableData.total" @change="onPageChange" @pageSizeChange="changeSize" />
	  </view>
	  
	   <!-- 添加选项对话框 -->
	      <uni-popup ref="dialogRef" type="dialog" destroy-on-close>
	        <uni-popup-dialog mode="input" :title="tableData.parent.name + '-' +(!formData.code ? '新增':'修改') + '选项'" :value="formData.code"
	          @confirm="confirmDialog(dictId)" @close="closeDialog()">
	          <view class="option-form">
	            <uni-forms ref="formRef" :modelValue="formData" :rules="formRules" validateTrigger="blur">
	              <uni-forms-item name="code" label="编码" required>
	                <uni-easyinput v-model="formData.code" placeholder="请输入选项编码" />
	              </uni-forms-item>
	              <uni-forms-item name="text" label="显示文本" required>
	                <uni-easyinput v-model="formData.text" placeholder="请输入显示文本" />
	              </uni-forms-item>
	              <uni-forms-item name="description" label="详细说明">
	                <uni-easyinput v-model="formData.description" placeholder="请输入详细说明" />
	              </uni-forms-item>
	              <uni-forms-item name="status" label="状态">
	                <switch v-model="formData.status" />
	              </uni-forms-item>
	              <uni-forms-item name="sort" label="排序">
	                <uni-easyinput type="number" v-model="formData.sort" placeholder="请输入排序值" />
	              </uni-forms-item>
	            </uni-forms>
	          </view>
	        </uni-popup-dialog>
	      </uni-popup>

    </view>
  </view>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { useTableSearch } from '@/utils/composable.js'
  
  const wallpaperObj = uniCloud.importObject('iss-wallpaper')
  const tableRef = ref(null)
  
  const dialogRef = ref(null)
  const formRef = ref(null)

  const dictId = ref('')
  onLoad((e) => {
    dictId.value = e.id
  })
  
  // 在页面层实现 composable.js 加载数据getList() 示范
  const getList = async () => {
    try {
      const empty = { data: { list: [], total: 0 } }
      const res = await wallpaperObj.doc_dict(dictId.value)
      
      if (res.code === 200) {
        // 对 options 按照 sort 字段进行倒序排序
        const sortedOptions = (res.data.options || []).sort((a, b) => {
          const sortA = a.sort || 0
          const sortB = b.sort || 0
          return sortB - sortA // 倒序排列
        })
  
        // 分页处理
        const page = Number(query.value.page) || 1
        const pageSize = Number(query.value.pageSize) || 10
        const startIndex = (page - 1) * pageSize
        const endIndex = page * pageSize
        const paginatedList = sortedOptions.slice(startIndex, endIndex)
		
        return {
		  code: 200,
          data: {
            list: paginatedList,
            total: sortedOptions.length || 0
          }
        }
      }
      return empty
    } catch (e) {
      console.error('加载字典选项失败:', e)
      return empty
    }
  }
  
  // 在页面层实现 composable.js 加载数据getParentData() 示范
  const getParentData = async () => {
    try {
      const res = await wallpaperObj.doc_dict(dictId.value)
      return res.data
    } catch (e) {
      console.error('加载字典选项失败:', e)
      return null
    }
  }
  
  // 在页面层对columnToggle的方法的实现示范（当然也可以将实现放到云对象中实现)
  const columnToggle = (code, fieldName) => {
    return new Promise(async (resolve, reject) => {
      try {
        if (fieldName === 'status') {
          const res = await wallpaperObj.toggleOptionStatus_dict(dictId.value, code);
          if (res.code === 200) {
            resolve(); // Resolve when everything succeeds
          } else {
            reject(new Error('状态切换失败:' + (res.msg || ''))); // Reject with error message
          }
        } else {
          reject(new Error(fieldName+'字典不存在'));
        }
      } catch (e) {
        reject(new Error('状态切换失败:' + e)); // Reject with caught error
      }
    });
  };
  
  // 在页面层对remove的方法的实现示范（当然也可以将实现放到云对象中实现)
  const remove = (code) => {
    return new Promise(async (resolve, reject) => {
      try {

		const res = await wallpaperObj.removeOption_dict(dictId.value, code);
		if (res.code === 200) {
			resolve(); // Resolve when everything succeeds
		} else {
			reject(new Error('删除失败:' + (res.msg || ''))); // Reject with error message
		}
        
      } catch (e) {
        reject(new Error('删除失败:' + e)); // Reject with caught error
      }
    });
  };
  
  // ######################以下是表单部分####################################
  
  // 新增时，默认表单内容
  const initFormData = {
	  code: '',
	  sort: 0,
	  text: '',
	  status: false,
	  description: ''
  }
  
  // 在页面层实现 composable.js 加载表单数据getFormData 示范
  const getFormData = (code, pid) => {
	  return new Promise( (resolve, reject) => {
		  try {
			  const opt = tableData.value.list.find(item => item.code == code)
			  if(opt) {
				  resolve({data:opt})
			  } else {
				  reject(new Error('未找到'+code+'对应的数据')); 
			  }
		  	
		  } catch (error) {
		  	reject(new Error('未找到'+code+'对应的数据'+error))
		  }
	  });
  }
  
  // 选项表单验证规则
  const formRules = ref({
    code: {
      rules: [{
        required: true,
        errorMessage: '请输入选项编码'
      }, {
        minLength: 1,
        maxLength: 50,
        errorMessage: '编码长度在1到50个字符'
      }, {
        validateFunction: (rule, value, data, callback) => {
          // 前端校验code是否唯一
          const exists = tableData.value.list.some(item => {
            // 编辑时排除当前项
            if (formData.value.code && item.code === formData.value.code) {
              return false
            }
            return item.code === value
          })
          if (exists) {
            callback('编码已存在，请重新输入')
          }
          return true
        }
      }]
    },
    text: {
      rules: [{
        required: true,
        errorMessage: '请输入显示文本'
      }, {
        minLength: 1,
        maxLength: 100,
        errorMessage: '显示文本长度在1到100个字符'
      }, {
        validateFunction: (rule, value, data, callback) => {
          // 前端校验text是否唯一
          const exists = tableData.value.list.some(item => {
            // 编辑时排除当前项
            if (formData.value.code && item.code === formData.value.code) {
              return false
            }
            return item.text === value
          })
          if (exists) {
            callback('显示文本已存在，请重新输入')
          }
          return true
        }
      }]
    },
    sort: {
      rules: [{
        format: 'int',
        errorMessage: '排序必须为整数'
      }]
    }
  })
	
	// 在页面层实现 composable.js 新增表单数据add 示范
	const add = (data, pid) => {
		return new Promise(async (resolve, reject) => {
		  try {
		
			const res = await wallpaperObj.addOption_dict(pid, data)

			if (res.code === 200) {
				resolve(); // Resolve when everything succeeds
			} else {
				reject(new Error('新增失败:' + (res.msg || ''))); // Reject with error message
			}
		    
		  } catch (e) {
		    reject(new Error('新增失败:' + e)); // Reject with caught error
		  }
		});
	}
	
	// 在页面层实现 composable.js 修改表单数据update 示范
	const update = (data, pid) => {
		return new Promise(async (resolve, reject) => {
		  try {
			const res = await wallpaperObj.updateOption_dict(pid, data.code, data)
			
			if (res && res.code === 200) {
				resolve(); // Resolve when everything succeeds
			} else {
				reject(new Error('修改失败:' + (res.msg || ''))); // Reject with error message
			}
		    
		  } catch (e) {
		    reject(new Error('修改失败:' + e)); // Reject with caught error
		  }
		});
	}

  
  // 使用通用表格搜索逻辑
  const {
	query,
    tableData, // 列表数据集合 ref对象
    getData, // 获取列表数据 method
    removeDataByIds, // 根据选择删除记录
    toggleFieldChange, // 列表中某条记录状态变化事件 method
	selectionChange, // 列表选中记录变化 method
	showDialog, // 打开新增/修改窗口
	closeDialog, // 关闭新增/修改窗口
	confirmDialog, // 提交新增/修改窗口
	formData, // 表单数据
	onPageChange,
	changeSize
  } = useTableSearch({
    title: '字典选项',
    tableRef,
    getList,
	getParentData,
	columnToggle,
	remove,
	dialogRef,
	formRef,
	initFormData,
	getFormData,
	add,
	update
  })
  

</script>

<style scoped lang="scss">
.uni-header {
  .uni-title {
    margin-left: 10px;
    font-size: 16px;
    font-weight: bold;
  }
}

.option-form {
  padding: 15px;
  
  ::v-deep .uni-forms-item__label {
    width: 80px !important;
  }
}


/* 解决 uni-app uni-table 横向滚动条导致左侧边框高度异常问题 */
::v-deep .table--border {
  border: none;
}

::v-deep .uni-table {
  border: 1px solid #ebeef5;
  border-right: none;
  border-bottom: none;
}

::v-deep .uni-table-th, 
::v-deep .uni-table-td {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
</style>